package com.gdth.utils;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class TimerInstance {
	
	private static class TimerHelper {
		public final static TimerInstance instance = new TimerInstance();
	}
	
	public static final TimerInstance getInstance() {
		return TimerHelper.instance;
	}
	
	private TimerInstance() {
		
	}
	
	/**
     * 计时器
     */
    private Timer timer;
    
    private CountdownTask task;
    
    private boolean isPause = false;
	
	/**
	 * 新建一个计时器
	 * @param handler
	 */
	public void CreateTask(Handler handler){
		task = new CountdownTask();
		task.setHandler(handler);
		timer = new Timer(); 
		timer.schedule(task, 1000, 1000);
	}
	
	public void stop(){
		isPause = false;
		
	}
	
	public void pause(){
		isPause = true;
	}
	
	public void restart(){
		isPause = true;
		task.setrecLen(0);
	}
	
	public void setTimeout(int time){
		task.setTimeout(time);
	}
	
	/**
	 * 计时器
	 * @author arvin
	 *
	 */
	class CountdownTask extends TimerTask{
		private Handler handler;
		
		private int recLen = 0;
		
		private int timeout = 5 * 60;
		
		public void setHandler(Handler handler){
			this.handler = handler;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (isPause){
				recLen += 1; 
				
				if (recLen < timeout) {
		            Message message = new Message();  
		            message.what = 1;
		            
		            Bundle bundle = new Bundle();
		            bundle.putInt("time", recLen);
		            
		            message.setData(bundle);
		            
		            handler.sendMessage(message); 
				} else {
					Message message = new Message();  
		            message.what = 2;
		            
		            handler.sendMessage(message);
		            isPause = false;
				}
			}
		}  
        
		public void setrecLen(int val){
			this.recLen = val;
		}
		
		public void setTimeout(int val){
			this.timeout = val * 60;
		}
    };  
}
